package com.nbsaas.boot.sql;

import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;

public class SqlConditionAppender {
    public static String addConditionToMainQuery(String sql, Expression newCondition) throws Exception {
        Statement stmt = CCJSqlParserUtil.parse(sql);
        if (stmt instanceof Select) {
            PlainSelect plainSelect = (PlainSelect) ((Select) stmt).getSelectBody();

            Expression oldWhere = plainSelect.getWhere();
            if (oldWhere == null) {
                plainSelect.setWhere(newCondition);
            } else {
                plainSelect.setWhere(new AndExpression(oldWhere, newCondition));
            }
            return stmt.toString();
        }
        return sql;
    }

    public static void main(String[] args) throws Exception {
        String sql = "SELECT id, name FROM (SELECT id, name FROM users WHERE age > 20) t";
        Expression condition = CCJSqlParserUtil.parseCondExpression("t.id < 100");

        String result = addConditionToMainQuery(sql, condition);
        System.out.println(result);
        // 输出: SELECT id, name FROM (SELECT id, name FROM users WHERE age > 20) t WHERE t.id < 100
    }
}
